from urllib.request import urlopen
from ftplib import FTP
import ftplib
import os
import re
import time


encoding_list = ['utf-8', 'gbk', 'gb2312', 'gb18030', 'big5', 'hz']

encoding_list = ['utf-8', 'gbk', 'gb2312', 'gb18030', 'big5', 'hz']


class FtpServer:
    ftp = None
    root = None
    _pwd = "/"

    def __init__(self, host, port, encoding = "gbk"):
        self.ftp = FTP(host, encoding=encoding)
        self.ftp.login()
        self._pwd = self.root = self.ftp.pwd()
        print("连接服务器成功")


    @property
    def pwd(self):
        if not self.is_connect():
            return "未连接 >"
        return self.ftp.pwd()

    def is_connect(self):
        return self.ftp != None


    def get_list_of_type(self, t=None, path=None) -> list((str, dict)):
        tests = []
        if (path == None):
            path = os.path.join(self.pwd + '/')
            self.ftp.cwd(path)
        for name, info in self.ftp.mlsd():
            if t == None:
                tests.append((name, info))
            elif info['type'] == t:
                tests.append((name, info))
        return tests

    # encoding 错误时，自动切换encoding尝试

    def auto_change_encoding(self, callback):
        for encoding in encoding_list:
            try:
                self.ftp.encoding = encoding
                return callback()
            except UnicodeDecodeError:
                pass
            except Exception:
                pass

    def change_dir(self, dirname: str):
        if not os.path.isabs(dirname):
            dirname = os.path.join(self.pwd, dirname)
        else:
            dirname = os.path.join(self.root, dirname)
        try:
            self.ftp.cwd(dirname)
        except Exception:
            print("切换目录到 %s 失败" % dirname)
